#include "control_modes.h"
#include "mode_cooling.h"
#include "mode_cleaning.h"
#include "mode_thawing.h"
#include "mode_preservation.h"
#include "actuator_control.h"
#include "sensors.h"
#include "config.h"
#include <stdio.h>
#include <string.h>

// 系统状态

static struct 
{
    bool initialized;
     RunningMode target_mode;
    RunningMode current_mode;
} RunningModeState;

// 模式处理函数指针
typedef struct {
    void (*init)(const SystemConfig *config);
    void (*enter)(void);
    void (*exit)(void);
    ModeStatus (*process)(void);
} ModeFunctions;

// 模式函数表
static const ModeFunctions mode_functions[] = {
    [MODE_IDLE] = {NULL, NULL, NULL, NULL},
    [MODE_COOLING] = {mode_cooling_init, mode_cooling_enter, mode_cooling_exit, mode_cooling_process},
    [MODE_CLEANING] = {mode_cleaning_init, mode_cleaning_enter, mode_cleaning_exit, mode_cleaning_process},
    [MODE_THAWING] = {mode_thawing_init, mode_thawing_enter, mode_thawing_exit, mode_thawing_process},
    [MODE_PRESERVATION] = {mode_preservation_init, mode_preservation_enter, mode_preservation_exit, mode_preservation_process},
};


void running_mode_init()
{    
  config_init();
   const SystemConfig *config = config_get();
    for (int i = 0; i < sizeof(mode_functions)/sizeof(mode_functions[0]); i++) {

        if (mode_functions[i].init) {
            mode_functions[i].init(config);
        }
    }
    RunningModeState.current_mode = MODE_IDLE;
    RunningModeState.initialized = true;
}
// 获取当前模式
RunningMode control_get_current_mode(void) {
    return RunningModeState.current_mode;
}

// 切换到指定模式
bool control_switch_mode(RunningMode mode)
{
    if (!RunningModeState.initialized || mode >= sizeof(mode_functions)/sizeof(mode_functions[0])) {
        return false;
    }
    RunningModeState.target_mode=mode;
    return true;
}

// 退出当前模式
void control_exit_mode(void) {
    control_switch_mode(MODE_IDLE);
}

// 处理当前模式逻辑
void running_mode_process(void)
 {

    if(RunningModeState.target_mode != RunningModeState.current_mode)
    {
        RunningMode mode =RunningModeState.target_mode;
           // 退出当前模式
        if (RunningModeState.current_mode != MODE_IDLE && mode_functions[RunningModeState.current_mode].exit) 
        {
            mode_functions[RunningModeState.current_mode].exit();
        }
        // 进入新模式
        RunningModeState.current_mode = mode;
        if (mode != MODE_IDLE && mode_functions[mode].enter) 
        {
            mode_functions[mode].enter();
        }
    }
    if (!RunningModeState.initialized || RunningModeState.current_mode == MODE_IDLE || 
        !mode_functions[RunningModeState.current_mode].process) 
    {
        return;
    }
    
    ModeStatus status = mode_functions[RunningModeState.current_mode].process();
    
    // 如果模式已完成或出错，切换到空闲模式
    if (status == MODE_STATUS_COMPLETE || status == MODE_STATUS_ERROR) {
        control_exit_mode();
    }
    
}
    